package cn.gong.jizhang.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.os.Debug;

import cn.gong.jizhang.config.PhoneParameters;

public class ObjectUtils {
	
	public static void cacheObjByMd5(Object obj, String path, long name) {
		cacheObj(obj, path, Md5Utils.MD5(name));
	}
	
	public static void cacheObjByMd5(Object obj, String path, int name) {
		cacheObj(obj, path, Md5Utils.MD5(name));
	}

	public static void cacheObjByMd5(Object obj, String path, String name) {
		cacheObj(obj, path, Md5Utils.MD5(name));
	}

	private static void cacheObj(Object obj, String path, String name) {
		ObjectOutputStream oos = null;
		FileOutputStream fos = null;
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			fos = new FileOutputStream(new File(file, name));
			oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
			fos.flush();
		} catch (Exception e) {
			DebugUtils.exception(e);
		} finally {
			try {
				if (oos != null) {
					oos.close();
				}
			} catch (IOException e) {
				DebugUtils.exception(e);
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
				} catch (IOException e) {
					DebugUtils.exception(e);
				}
			}
		}
	}

	public static Object getObjByMd5(String path, long name) {
		return getObjByOriName(path, Md5Utils.MD5(name));
	}
	
	public static Object getObjByMd5(String path, int name) {
		return getObjByOriName(path, Md5Utils.MD5(name));
	}
	
	public static Object getObjByMd5(String path, String name) {
		return getObjByOriName(path, Md5Utils.MD5(name));
	}

	public static Object getObjByOriName(String path, String name) {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(path + name);
			ois = new ObjectInputStream(fis);
			Object readObject = ois.readObject();
			fis.close();
			ois.close();
			return readObject;
		} catch (Exception e) {
			DebugUtils.exception(e);
			return null;
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (Exception e) {
				DebugUtils.exception(e);
			} finally {
				try {
					if (ois != null) {
						ois.close();
					}
				} catch (Exception e) {
					DebugUtils.exception(e);
				}
			}
		}
	}
}
